package com.zhucai.credit.bank.service.cron;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Strings;
import com.zhucai.common.locks.DistributedLockFactory;
import com.zhucai.common.locks.DistributedReentrantLock;
import com.zhucai.credit.bank.ccbe.bean.CreditRecordDebit;
import com.zhucai.credit.bank.ccbe.bean.CreditRecordFeedback;
import com.zhucai.credit.bank.ccbe.bean.CreditRecordPayment;
import com.zhucai.credit.bank.ccbe.bean.DrawFinancingMoney;
import com.zhucai.credit.bank.ccbe.bean.SignUpFeedback;
import com.zhucai.credit.bank.ccbe.bean.SignUpFeedbackTwo;
import com.zhucai.credit.bank.ccbe.bean.SignUpInfo;
import com.zhucai.credit.bank.ccbe.service.CcbeService;
import com.zhucai.credit.common.CommonEnums.CrAprovalStatus;
import com.zhucai.credit.common.CommonEnums.CrProdType;
import com.zhucai.credit.common.CommonEnums.CrProdstatus;
import com.zhucai.credit.common.CommonEnums.CreditStatus;
import com.zhucai.credit.common.CommonEnums.CreditUnusualStatus;
import com.zhucai.credit.common.CommonEnums.EnCrStatus;
import com.zhucai.credit.common.CommonEnums.EntType;
import com.zhucai.credit.common.CommonEnums.OperType;
import com.zhucai.credit.common.CommonEnums.ZhuCaiProdType;
import com.zhucai.credit.common.HelpConstant;
import com.zhucai.credit.common.ZhucaiConstant;
import com.zhucai.credit.model.ContractList;
import com.zhucai.credit.model.CreditApplicationEntity;
import com.zhucai.credit.model.CreditInvoiceEntity;
import com.zhucai.credit.model.CreditProductEntity;
import com.zhucai.credit.model.CreditRecordEntrity;
import com.zhucai.credit.model.CreditRecordTimeEntrity;
import com.zhucai.credit.model.EntAccountEntity;
import com.zhucai.credit.model.EntCrProdEntity;
import com.zhucai.credit.model.FinanceDrawEntity;
import com.zhucai.credit.model.FinanceRepaymentEntity;
import com.zhucai.credit.model.OperRecordEntity;
import com.zhucai.credit.model.OrderList;
import com.zhucai.credit.model.PaymentPlanEntity;
import com.zhucai.credit.model.ProblemRecordEntrity;
import com.zhucai.credit.repository.ContractListRepository;
import com.zhucai.credit.repository.CreditApplicationRepository;
import com.zhucai.credit.repository.CreditInvoiceRepository;
import com.zhucai.credit.repository.CreditProductRepository;
import com.zhucai.credit.repository.CreditRecordRepository;
import com.zhucai.credit.repository.CreditRecordTimeRepository;
import com.zhucai.credit.repository.EntAccountRepository;
import com.zhucai.credit.repository.EntCrProdEntityRepository;
import com.zhucai.credit.repository.FinanceDrawRepository;
import com.zhucai.credit.repository.FinanceRepaymentRepository;
import com.zhucai.credit.repository.OperRecordRepository;
import com.zhucai.credit.repository.OrderListRepository;
import com.zhucai.credit.repository.PaymentPlanRepository;
import com.zhucai.credit.service.impl.problem.ProblemSericeImpl;
import com.zhucai.credit.service.impl.transactional.CreditUserServiceUtil;
import com.zhucai.credit.service.impl.transactional.MessageServiceImpl;
import com.zhucai.credit.utils.TimeUtils;

/**
 * 金融接口的定时循环任务 2017年11月28日
 * 
 * @author hsg
 */
//@Service
public class CcbEPointLoopService {
	private static final Logger logger = LoggerFactory.getLogger(CcbEPointLoopService.class);
	@Autowired
	private EntAccountRepository entAccountRepository;
	@Autowired
	private ContractListRepository contractListRepository;
	@Autowired
	private OperRecordRepository operRecordRepository;
	@Autowired
	private CreditRecordRepository creditRecordRepository;
	@Autowired
	private CreditProductRepository creditProductRepository;
	@Autowired
	private EntCrProdEntityRepository entCrProdEntityRepository;
	@Autowired
	private FinanceDrawRepository financeDrawRepository;
	@Autowired
	private FinanceRepaymentRepository financeRepaymentRepository;
	@Autowired
	CreditApplicationRepository creditApplicationRepository;
	@Autowired
	private PaymentPlanRepository paymentPlanRepository;
	@Autowired
	private DistributedLockFactory distributedLockFactory;
	@Autowired
	private CcbeService ccbeService;
	@Autowired
	private ProblemSericeImpl problemSericeImpl;
	@Autowired
	private MessageServiceImpl messageServiceImpl;
	@Autowired
	private OrderListRepository orderListRepository;
	@Autowired
	private CreditInvoiceRepository creditInvoiceRepository;
	@Autowired
	private CreditUserServiceUtil creditUserServiceUtil;
	@Autowired
	private CreditRecordTimeRepository creditRecordTimeRepository;

	@Scheduled(fixedRate = 500000)
	public void signUpTask() {
		logger.trace("loop：signUpTask start");
		DistributedReentrantLock lock = distributedLockFactory.buildLock("signUpTaskLock");
		if (lock.tryLock(1000)) {
			try {
				try {
					findSignUpInfo();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} finally {
				lock.unlock();
				logger.trace("loop：signUpTask complete");
			}
		} else {
			logger.trace("loop：signUpTask is running in other jvm ,this thread end");
		}
	}

	@Scheduled(fixedRate = 500000)
	public void approveSignUpInfoLoop() throws Exception {
		logger.trace("loop：approveSignUpInfo start");
		DistributedReentrantLock lock = distributedLockFactory.buildLock("approveSignUpInfoLoop_Count");
		if (lock.tryLock(1000)) {
			try {
				approveSignUpInfo();
			} finally {
				lock.unlock();
				logger.trace("loop：approveSignUpInfo complete");
			}
		} else {
			logger.trace("loop：approveSignUpInfo is running in other jvm ,this thread end");
		}
	}

	@Scheduled(fixedRate = 500000)
	public void approveSignUpInfoToLoop() {
		logger.trace("loop：approveSignUpInfoTo start");
		DistributedReentrantLock lock = distributedLockFactory.buildLock("approveSignUpInfoTo");
		if (lock.tryLock(1000)) {
			try {
				approveSignUpInfoTo();
			} finally {
				lock.unlock();
				logger.trace("loop：approveSignUpInfoTo complete");
			}
		} else {
			logger.trace("loop：approveSignUpInfoTo is running in other jvm ,this thread end");
		}
	}

	@Scheduled(fixedRate = 500000)
	public void findCreditRecordFeedBackLoop() {
		logger.trace("loop：findCreditRecordFeedBack start");
		DistributedReentrantLock lock = distributedLockFactory.buildLock("findCreditRecordFeedBack");
		if (lock.tryLock(1000)) {
			try {
				findCreditRecordFeedBack();
			} finally {
				lock.unlock();
				logger.trace("loop：findCreditRecordFeedBack complete");
			}
		} else {
			logger.trace("已有过期任务处理中，忽略本次执行");
		}
	}

	/**
	 * 支用信息反馈 6W5528循环任务
	 * 
	 * @date 2017年11月29日 @user hsg
	 */
	@Scheduled(fixedRate = 500000)
	public void drawMoneyFeedBackLoop() {
		logger.trace("drawMoneyFeedBackLoop start");
		DistributedReentrantLock lock = distributedLockFactory.buildLock("drawMoneyFeedBackLoop");
		if (lock.tryLock(1000)) {
			try {
				try {
					drawMoneyFeedBack();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} finally {
				lock.unlock();
				logger.trace("loop：drawMoneyFeedBackLoop complete");
			}
		} else {
			logger.trace("已有过期任务处理中，忽略本次执行");
		}
	}
	/**
	 * 付款反馈的循环任务 6W5564
	 * 
	 * @date 2017年11月30日 @user hsg
	 */
	@Scheduled(fixedRate = 500000)
	public void findCreditRecordPaymentLoop() {
		logger.trace("findCreditRecordPayment start");
		DistributedReentrantLock lock = distributedLockFactory.buildLock("findCreditRecordPayment");
		if (lock.tryLock(1000)) {
			try {
				try {
					findCreditRecordPayment();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} finally {
				lock.unlock();
				logger.trace("loop：findCreditRecordFeedBack complete");
			}
		} else {
			logger.trace("已有过期任务处理中，忽略本次执行");
		}
	}
	/**
	 * 扣款信息反馈的循环任务 6W5550
	 * 
	 * @date 2017年11月30日 @user hsg
	 */
	@Scheduled(fixedRate = 500000)
	public void findCreditRecordDebitLoop() {
		logger.trace("findCreditRecordDebit start");
		DistributedReentrantLock lock = distributedLockFactory.buildLock("findCreditRecordDebit");
		if (lock.tryLock(1000)) {
			try {
				try {
					findCreditRecordDebit();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} finally {
				lock.unlock();
				logger.trace("loop：findCreditRecordFeedBack complete");
			}
		} else {
			logger.trace("已有过期任务处理中，忽略本次执行");
		}
	}

	/**
	 * ADD 查询建行报名信息查询
	 * @throws Exception 
	 * 6W5501
	 * @date 2017年11月29日 @user hsg
	 */
	private void findSignUpInfo() throws Exception {
			
		//报名反馈序号（无实际用处，记录问题）
		String customer_app_serial_num = null;
		try {
			// 调用建行接口返回报名信息的list
			List<SignUpInfo> signUpInfoList = ccbeService.signUpInfo();
			if (CollectionUtils.isEmpty(signUpInfoList)) {
				logger.info("调用建行接口返回报名信息的list为空！！");
				return;
			}
			for (SignUpInfo signUpInfo : signUpInfoList) {
				customer_app_serial_num = signUpInfo.getCustomer_app_serial_num()+"";
				if (Strings.isNullOrEmpty(signUpInfo.getCo_Entp_Org_InsNo())) {
					logger.info("申请组织机构为" + signUpInfo.getOrgn_num() + "合作组织为空，");
					continue;
				}
				// 根据报名编号判断是否存在
				CreditApplicationEntity cae = creditApplicationRepository.findByAppNumAndStatusNot(signUpInfo.getApp_num(), HelpConstant.Status.delete);
				if (cae != null) {
					//已存在
					continue;
				}
				// 新增一条新的贷款资质申请记录
				CreditApplicationEntity newCae = createApplication(signUpInfo);
				if(newCae==null){
					//当为null跳出循环
					continue;
				}
				creditApplicationRepository.save(newCae);
				// 根据组织机构id查询筑保通信息
				EntCrProdEntity ecpe = entCrProdEntityRepository.findByStatusNotAndOrgnNumAndEntType(HelpConstant.Status.delete, signUpInfo.getOrgn_num(),EntType.SUPPLIER.toString(),newCae.getCrProdId());
				EntAccountEntity entAccountEntity = entAccountRepository.findByStatusNotAndOrgNumAndEntType(HelpConstant.Status.delete, signUpInfo.getOrgn_num(),EntType.SUPPLIER.toString());
				if(ecpe == null) {
					if(entAccountEntity == null) {
						logger.error("### 查询建行报名信息查询--根据建行返回的供应商企业名称enter_name={},的组织机构代码sup_org_num={},查询金融信息为空", signUpInfo.getCustomer_name(),signUpInfo.getOrgn_num());
						continue;
					}
					
					// 新增筑保通信息
					EntCrProdEntity ecpes = new EntCrProdEntity();
					ecpes.setEntType(EntType.SUPPLIER.toString());
					ecpes.setEnAccId(entAccountEntity.getTid());
					// 根据贷款机构类型查询贷款机构信息
					CreditProductEntity cpe = creditProductRepository.findByCrProdTypeAndStatusNot(
							CrProdType.E_POINT.toString(), HelpConstant.Status.delete);
					if (cpe != null) {
						ecpes.setCrPrTypeId(cpe.getTid());
					}
					ecpes.setEnterpriseId(entAccountEntity.getEnterpriseId());
					ecpes.setCrProdRateStr("基准利率");
					ecpes.setOrgnNum(signUpInfo.getOrgn_num());
					ecpes.setZhucaiProdType(ZhuCaiProdType.ZHU_CAI_B_TONG.toString());
					/**
					 * 新增时默认为融资率为1%
					 */
					ecpes.setCrProdRate(BigDecimal.ONE);
					ecpes.setEnCrStatus(EnCrStatus.APPROVALING.toString());
					ecpes.setModifyDescription("查询建行报名信息查询自动生成");
					ecpes.setEcpStatus(0);
					ecpes.setApplyTime(new Date());
					entCrProdEntityRepository.save(ecpes);
				}
				try {
					//采购商资金总调度收到站内信
					EntAccountEntity eae_pur = entAccountRepository.findByStatusNotAndOrgNumAndEntType(HelpConstant.Status.delete,
							signUpInfo.getCo_Entp_Org_InsNo(),EntType.PURCHASER.toString());
					EntAccountEntity eae_sup = entAccountRepository.findByStatusNotAndOrgNumAndEntType(HelpConstant.Status.delete,
							signUpInfo.getOrgn_num(),EntType.SUPPLIER.toString());
					//采购商的超管id
					Long purUserId = entAccountRepository.findPurUserId(eae_pur.getTid());
					//供应商的超管id
					Long supUserId = entAccountRepository.findSupUserId(eae_sup.getTid());
					Long user_zdd_id=entAccountRepository.findZDDId(purUserId,HelpConstant.Status.delete);
					List<Long> ids = new ArrayList<Long>();
					ids.add(user_zdd_id);
					List<String> parm = new ArrayList<String>();
					parm.add(newCae.getTid().toString());
					
					messageServiceImpl.sendMessage(supUserId.toString(), "P57", null, ids , parm);
				} catch (Exception e) {
					// TODO: handle exception
					logger.error("### 查询建行报名信息时发送站内信失败 errMsg={}",e);
				}
				
			}
		} catch (Exception e) {
			logger.error("查询建行报名信息发生异常，报名反馈序号customer_app_serial_num={},异常 errMsg={}", customer_app_serial_num,e);
			/**
			 * 问题记录
			 */
			String problem = "查询建行报名信息发生异常，报名反馈序号customer_app_serial_num="+customer_app_serial_num+"异常 errMsg="+e;
			problemSericeImpl.setProblem(problem,"6W5501");
		}
			

	}

	private CreditApplicationEntity createApplication(SignUpInfo ca) {

		CreditApplicationEntity newCea = new CreditApplicationEntity();
		newCea.setApplicantEnterpriseName(ca.getCustomer_name());
		newCea.setApplicantMobile(ca.getApplicant_phone());
		newCea.setApplicantName(ca.getApplicant_name());
		newCea.setApplicantPhone(ca.getApplicant_fix_phone());
		newCea.setAppNum(ca.getApp_num());
		newCea.setAppOrgnNum(ca.getOrgn_num());
		newCea.setCooOrgnNum(ca.getCo_Entp_Org_InsNo());
		newCea.setApplyAmt(ca.getApply_amt());
		newCea.setCrProdstatus(CrProdstatus.WAIT_APPROVAL.toString());
		// 查询供应商的金融信息id
		EntAccountEntity eae_sup = entAccountRepository.findByStatusNotAndOrgNumAndEntType(HelpConstant.Status.delete,
				ca.getOrgn_num(),EntType.SUPPLIER.toString());
		if (eae_sup != null) {
			newCea.setCrApplicantId(eae_sup.getTid());
		}else{
			logger.error("### 查询建行报名信息查询--根据建行返回的供应商企业名称enter_name={},的组织机构代码sup_org_num={},查询金融信息为空", ca.getCustomer_name(),ca.getOrgn_num());
			/**
			 * 问题记录
			 */
			String problem = "根据建行返回的供应商企业名称enter_name="+ca.getCustomer_name()+"和组织机构代码sup_org_num="+ca.getOrgn_num()+"查询金融信息为空！！";
			problemSericeImpl.setProblem(problem,"6W5501");
			
			return null;
		}
		newCea.setApplicantEnterpriseId(eae_sup.getEnterpriseId());
		// 查询采购商的金融信息id
		EntAccountEntity eae_pur = entAccountRepository.findByStatusNotAndOrgNumAndEntType(HelpConstant.Status.delete,
				ca.getCo_Entp_Org_InsNo(),EntType.PURCHASER.toString());

		if (eae_pur != null) {
			newCea.setCrApplicantPurId(eae_pur.getTid());
		}else{
			logger.error("### 查询建行报名信息查询--根据建行返回的核心企业名称enter_name={},的组织机构代码pur_org_num={},查询金融信息为空", ca.getPltfrm_Nm(),ca.getCo_Entp_Org_InsNo());
			/**
			 * 问题记录
			 */
			String problem = "根据建行返回的核心企业名称enter_name="+ca.getPltfrm_Nm()+"和组织机构代码pur_org_num="+ca.getCo_Entp_Org_InsNo()+"查询金融信息为空！！";
			problemSericeImpl.setProblem(problem,"6W5501");
			return null;
		}
		// 查询建行e点通对应的id
		CreditProductEntity cpe = creditProductRepository.findByCrProdTypeAndStatusNot(CrProdType.E_POINT.toString(),
				HelpConstant.Status.delete);
		if (cpe != null) {
			newCea.setCrProdId(cpe.getTid());
		}else{
			logger.error("### 查询建行报名信息查询--查询e点通失败, creditProductRepository.findByCrProdTypeAndStatusNot(CrProdType.E_POINT.toString()");
			return null;
		}
		newCea.setCrAprovalStatus(CrAprovalStatus.BANK_AUDIT.toString());
		newCea.setCrApplyTime(new Date());
		return newCea;

	}

	/**
	 * 报名信息状态反馈 6W5503 查询建行审核报名的信息
	 * @throws Exception 
	 * 
	 * @date 2017年11月29日 @user hsg
	 */
	private void approveSignUpInfo() throws Exception {

		// 根据建行接口返回的信息
		List<SignUpFeedback> rs = null;
		//报名状态反馈序号(无实际用处，记录问题用的)
		String application_state_serial_num = "0";
		try {
			// 判断数据里是否有带建行审核的信息
			List<CreditApplicationEntity> crList = creditApplicationRepository.findByCrAprovalStatusAndStatusNot(
					CrAprovalStatus.DATA_REVIEW.toString(), HelpConstant.Status.delete);
			List<CreditApplicationEntity> crList2 = creditApplicationRepository.findByCrAprovalStatusAndStatusNot(
					CrAprovalStatus.PUR_CONFIRM_SUCCESS.toString(), HelpConstant.Status.delete);
			if (crList.isEmpty() && crList2.isEmpty()) {
				// 当我们没有待银行审核的不去查询
				return;
			}
			rs = ccbeService.signUpFeedback();
			if (rs.isEmpty()) {
				logger.info("### 查询建行审核报名的信息(approveSignUpInfo)--报名信息状态反馈 6W5503  查询结果为空");
				return;
			}
			for (SignUpFeedback signUpFeedback : rs) {
				application_state_serial_num = signUpFeedback.getApplication_state_serial_num()+"";
				// 根据报名编号查询资质申请信息
				CreditApplicationEntity cae = creditApplicationRepository
						.findByAppNumAndStatusNot(signUpFeedback.getApp_num(), HelpConstant.Status.delete);
				if (cae == null) {
					logger.error("### 查询建行审核报名的信息(approveSignUpInfo)--根据建行返回的报名编号app_num={}，查询贷款机构资质申请信息(CreditApplicationEntity)查询为空", signUpFeedback.getApp_num());
					/**
					 * 问题记录
					 */
					String problem = "根据建行返回的报名编号app_num={}"+signUpFeedback.getApp_num()+"查询贷款机构资质申请信息(CreditApplicationEntity)查询为空";
					problemSericeImpl.setProblem(problem,"6W5503");
					continue;
				}
				if (cae.getCrAprovalStatus().equals(CrAprovalStatus.DATA_REVIEW.toString())
						|| cae.getCrAprovalStatus().equals(CrAprovalStatus.PUR_CONFIRM_SUCCESS.toString())) {
					OperRecordEntity operRecordEntity = new OperRecordEntity();
					operRecordEntity.setModifyDescription("银行最终审核");
					operRecordEntity.setOperatorName(signUpFeedback.getApplicant_name());
					// 由于是建行返回的数据所以就随便写了个id
					operRecordEntity.setOperator(Long.valueOf(1));
					// 由于没返回时间所以就记录了当前写入时间
					operRecordEntity.setOperTime(new Date());
					operRecordEntity.setOperType(OperType.BANK_FINAL_APPROVE.toString());
					operRecordEntity.setOutId(cae.getTid());
					if (signUpFeedback.getApprove_pass_ind().equals("1")) {
						// 审核状态改为银行终审通过
						cae.setCrAprovalStatus(CrAprovalStatus.BANK_ACCOUNT_SUCCESS.toString());
						operRecordEntity.setBizKey("1");
						operRecordEntity.setResult("银行最终审核通过");
						operRecordEntity.setReview("银行最终审核通过的原因：");
					} else if (signUpFeedback.getApprove_pass_ind().equals("0")) {
						// 审核状态改为银行终审不通过
						cae.setCrAprovalStatus(CrAprovalStatus.BANK_ACCOUNT_REJECT.toString());
						operRecordEntity.setBizKey("0");
						operRecordEntity.setResult("银行最终审核不通过");
						operRecordEntity.setReview("银行最终审核不通过的原因：" + signUpFeedback.getUnpass_reason());
					}
					operRecordRepository.save(operRecordEntity);
					cae.setCrProdstatus(CrProdstatus.WAIT_APPROVAL.toString());
					Integer coo = creditApplicationRepository.updateStatus(cae.getTid(),cae.getCrAprovalStatus(),cae.getCrProdstatus());
					if(coo != 1){
						logger.error("查询建行审核报名的信息发生（approveSignUpInfo），报名状态反馈序号application_state_serial_num={},异常 errMsg={}", application_state_serial_num,"更新状态异常");
						/**
						 * 问题记录
						 */
						String problem = "查询建行审核报名的信息发生（approveSignUpInfo），报名状态反馈序号application_state_serial_num="+application_state_serial_num+"异常 errMsg=更新状态异常";
						problemSericeImpl.setProblem(problem,"6W5503");
					}
				}
			}
		} catch (Exception e) {
			logger.error("查询建行审核报名的信息发生（approveSignUpInfo），报名状态反馈序号application_state_serial_num={},异常 errMsg={}", application_state_serial_num,e);
			/**
			 * 问题记录
			 */
			String problem = "查询建行审核报名的信息发生（approveSignUpInfo），报名状态反馈序号application_state_serial_num="+application_state_serial_num+"异常 errMsg="+e;
			problemSericeImpl.setProblem(problem,"6W5503");
		}

	}

	/**
	 * 业务信息反馈 6W5519 查询建行审核报名业务信息反馈的信息
	 * 
	 * @date 2017年11月29日 @user hsg
	 */
	public void approveSignUpInfoTo() {

		// 根据建行接口返回的信息
		List<SignUpFeedbackTwo> rs = null;
		//反馈序号（记录问题用）
		String serial_num =null;
		try {
			// 判断数据里是否有建行审核通过的
			List<CreditApplicationEntity> caList = creditApplicationRepository.findByCrAprovalStatusAndStatusNot(
					CrAprovalStatus.BANK_ACCOUNT_SUCCESS.toString(), HelpConstant.Status.delete);
			if (caList.isEmpty()) {
				// 当我们没有建行审核通过的不去查询
				return;
			}
			rs = ccbeService.signUpFeedbackTwo();
			if (rs.isEmpty()) {
				return;
			}
			for (SignUpFeedbackTwo signUpFeedbackTwo : rs) {
				serial_num = signUpFeedbackTwo.getSerial_num()+"";
				// 根据报名编号查询资质申请记录
				CreditApplicationEntity cae = creditApplicationRepository
						.findByAppNumAndStatusNot(signUpFeedbackTwo.getRegist_num(), HelpConstant.Status.delete);
				if (cae == null) {
					
					logger.error("### 查询建行审核报名业务信息反馈的信息(approveSignUpInfoTo)--根据报名编号app_num={},查询资质申请记录（CreditApplicationEntity）为空", signUpFeedbackTwo.getRegist_num());
					continue;
				}
				if (!cae.getCrAprovalStatus().equals(CrAprovalStatus.BANK_ACCOUNT_SUCCESS.toString())) {
					//过滤不需要的数据
					continue;
				}
				// 查询出当前正在有效的记录把它改为过期
				CreditApplicationEntity caer = creditApplicationRepository.findPassCreditApplication(
						signUpFeedbackTwo.getCust_orgn_code(), signUpFeedbackTwo.getR_cust_orgn_code(),
						CrAprovalStatus.BANK_SUCCESS.toString(),cae.getCrProdId());
				if (caer != null) {
					caer.setCrAprovalStatus(CrAprovalStatus.OVER.toString());
					
					Integer coo = creditApplicationRepository.updateCrAprovalStatus(CrAprovalStatus.OVER.toString(),caer.getTid());
					if(coo != 1){
						logger.error("### 更新资质申请状态为过期异常，appId={}", caer.getTid());
					}
				}
				// 审核状态改为成功申请
				cae.setCrAprovalStatus(CrAprovalStatus.BANK_SUCCESS.toString());
				if (StringUtils.isNotEmpty(signUpFeedbackTwo.getContract_amt())) {
					Long contract_amt = Long.parseLong(signUpFeedbackTwo.getContract_amt());
					cae.setContractAmt(BigDecimal.valueOf(contract_amt));
				} else {
					cae.setContractAmt(BigDecimal.ZERO);
				}
				cae.setCrProdStartTime(TimeUtils.changeDate(signUpFeedbackTwo.getStart_date()));
				cae.setCrProdEndTime(TimeUtils.changeDate(signUpFeedbackTwo.getExdr_date()));
				cae.setContractNum(signUpFeedbackTwo.getContract_num());
				int termOfValidity = (int) TimeUtils.getBetween(signUpFeedbackTwo.getStart_date(),
						signUpFeedbackTwo.getExdr_date(), TimeUtils.YYYYMMDD_A, TimeUtils.YEAR_RETURN);
				cae.setTermOfValidity(termOfValidity);
				cae.setCrProdstatus(CrProdstatus.IN_COOPERATION.toString());
				cae.setClearanceAccount(signUpFeedbackTwo.getClearance_account());
				cae.setRecoverAccount(signUpFeedbackTwo.getRecover_account());
				creditApplicationRepository.save(cae);
				// 更新筑保通为通过
				entCrProdEntityRepository.updatePassByOrgnNum(cae.getAppOrgnNum(),cae.getCrProdId());
			}
		} catch (Exception e) {
			logger.error("### 查询建行审核报名业务信息反馈的信息发生异常 err={}", e);
			String problem = "查询建行审核报名业务信息反馈的信息发生异常，反馈序号serial_num="+serial_num+",异常 errMsg="+e;
			problemSericeImpl.setProblem(problem,"6W5519");
		}

	}

	/**
	 * 账款受让信息反馈（合同签订） 6W5549
	 * 
	 * @date 2017年11月29日 @user hsg
	 */
	public void findCreditRecordFeedBack() {
		logger.info("### 账款受让信息反馈（合同签订） 6W5549 start...");
		//记录第几次（用于条数多的时候）
		int count = 1;
		//反馈序号
		Integer serial_num = 0;
		try {
			List<String> creditStatusList = new ArrayList<String>();
			
			creditStatusList.add(CreditStatus.SUBSTITUTE_CONTRACT.toString());//代签合同
			creditStatusList.add(CreditStatus.PENDING_WITHDRAWAL.toString());//待支取
			creditStatusList.add(CreditStatus.REPAYMENT.toString());//待还款
			creditStatusList.add(CreditStatus.REPAYMENTS.toString());//已还款
			
			List<CreditRecordEntrity> crList = creditRecordRepository.findByCreditStatusAndStatusNot(
					creditStatusList, HelpConstant.Status.delete,CrProdType.E_POINT.toString());
			if (crList.isEmpty()) {
				// 判断是否有供应商确认通过的，如果无就不去查询
				return;
			}
			// 调用接口返回集合
			List<CreditRecordFeedback> rs = ccbeService.creditRecordFeedback();
			
			for (CreditRecordFeedback creditRecordFeedback : rs) {
				//记录序号用于记录问题
				serial_num = creditRecordFeedback.getSerial_num();
				
				//根据发票代码和发票编号查询融资记录
				CreditRecordEntrity cre = creditRecordRepository.findByStatusNotAndInvoiceNoCode(
						HelpConstant.Status.delete, creditRecordFeedback.getBill_num());
				
				if(cre==null){
					//当查询出的融资记录为空跳出循环
					logger.warn("### 发票号为InvoiceNoCode={},查询出的融资记录为空", creditRecordFeedback.getBill_num());
					/**
					 * 问题记录
					 */
					String problem = "反馈序号="+serial_num+"账款受让信息反馈6W5549在第"+count+"次发生异常,InvoiceNoCode="+creditRecordFeedback.getBill_num()+"查询融资记录为空！！";
					problemSericeImpl.setProblem(problem,"6W5549");
					
					continue;
				}
				logger.info("### 账款受让信息反馈（合同签订） 6W5549 循环start,InvoiceNoCode={},creditStatus={}",creditRecordFeedback.getBill_num(),cre.getCreditStatus());
				//查询计划付款记录
				PaymentPlanEntity ppe = paymentPlanRepository.findOne(cre.getPaymentId());
				if(ppe == null){
					//当查询出的计划付款记录为空跳出循环
					logger.warn("### 发票号为InvoiceNoCode={}的融资记录对应的计划付款id={},查询出的付款计划记录为空", creditRecordFeedback.getBill_num(),cre.getPaymentId());
					/**
					 * 问题记录
					 */
					String problem = "反馈序号="+serial_num+"账款受让信息反馈6W5549在第"+count+"次发生异常,InvoiceNoCode="+creditRecordFeedback.getBill_num()+"查询实际付款记录为空！！";
					problemSericeImpl.setProblem(problem,"6W5549");
					
					continue;
				}
				//判断融资记录是否被处理过
				if(ppe.getPayState() == 5 && ppe.getPlatformPayStatus() == 4 && cre.getLoanDateCcb()!=null && !cre.getCreditStatus().equals(CreditStatus.SUBSTITUTE_CONTRACT.toString())){
					continue;
				}
				/**
				 * 判断此融资记录的状态
				 */
				if (creditStatusList.contains(cre.getCreditStatus())) {
					
					signContract(cre,creditRecordFeedback);
					count++;
				}
			}
			
		} catch (Exception e) {
			
			logger.error("账款受让信息反馈 6W5549 发生异常 err={}",  e);
			/**
			 * 问题记录
			 */
			String problem = "反馈序号="+serial_num+"账款受让信息反馈6W5549在第"+count+"次发生异常"+e;
			problemSericeImpl.setProblem(problem,"6W5549");
		}
	}

	/**
	 * 合同签订方法
	 * @param cre
	 * @param creditRecordFeedback
	 */
	private void signContract(CreditRecordEntrity cre,CreditRecordFeedback creditRecordFeedback){
		logger.info("### 发票号为InvoiceNoCode={},融资状态creditStatus={},开始调用合同签订的方法signContract", creditRecordFeedback.getBill_num(),cre.getCreditStatus());
		PaymentPlanEntity ppe = paymentPlanRepository.findOne(cre.getPaymentId());
		//当为1时为合同签署成功
		if ("1".equals(creditRecordFeedback.getSuccess_ind())) {
			//判断当前的融资状态是否被更新过
			if(cre.getCreditStatus().equals(CreditStatus.SUBSTITUTE_CONTRACT.toString())){
				// 审核状态更新为待支取
				cre.setCreditStatus(CreditStatus.PENDING_WITHDRAWAL.toString());
			}
			//更新融资到期日
			cre.setLoanDateCcb(creditRecordFeedback.getAr_due_date());
			//判断付款计划的付款状态
			if(ppe.getPayState() != 5 && ppe.getPlatformPayStatus() != 4){
				//更新计划付款更新
				SimpleDateFormat sf2 = new SimpleDateFormat("yyyy-MM-dd");
				String nowDay = sf2.format(new Date());
				//实际付款时间和收款时间
				ppe.setPayForDate(nowDay);
				//采购商付款
				ppe.setPayState(5);
				//供应商收款
				ppe.setPlatformPayStatus(4);
				ppe.setPayForMethod(1);
				//委托集团付款方式
				ppe.setPayway("1");
				//直接付款
				ppe.setPayChannelType("1");
				//已付款金额
				ppe.setContractPaidAmount(ppe.getContractThisAmount());
				//实际付款金额
				ppe.setPayThisAmount(ppe.getContractThisAmount());
				//更新合同
				ContractList cl = contractListRepository.findBytidAndStatusNot(Long.valueOf(ppe.getContractId()), ZhucaiConstant.ContractListStatus.INVALID);
				//原来的合同付款金额（无实际用处，用来打印日志）
				Double oldContractAmt = cl.getContractPaidAmount();
				
				Double contractPaidAmount = cl.getContractPaidAmount();
				if(contractPaidAmount==null){
					cl.setContractPaidAmount(ppe.getContractThisAmount());
				}else{
					cl.setContractPaidAmount(contractPaidAmount+ppe.getContractThisAmount());
				}
				Integer unfinishedNum = paymentPlanRepository.findUnfinishedCountByOrderIdAndStatusNot(ppe.getOrderId(), new Long(ZhucaiConstant.PaymentPlanStatus.END_PAYMENT_STATUS), HelpConstant.Status.delete);
				if(unfinishedNum.equals(0)&&ppe.getOrderId()!=null){							//任务完成状态更新
					OrderList orderList = orderListRepository.findBytIdAndStatusNot(ppe.getOrderId(), HelpConstant.Status.delete);
					orderList.setOrderStatus(ZhucaiConstant.OrderStatus.COMPLETED_ORDER);
					orderListRepository.save(orderList);
					logger.info("### 6W5549建行签署合同成功，更新订单状态为已完成的订单成功OrderStatus={}",ZhucaiConstant.OrderStatus.COMPLETED_ORDER);
				}
				
				contractListRepository.save(cl);
				logger.info("### 6W5549建行签署合同成功，更新合同成功付款金额成功原来的付款金额oldContractAmt={},新增的付款金额newContractAmt={},相加后的付款金额nowContractAmt={}", oldContractAmt,ppe.getContractThisAmount(),cl.getContractPaidAmount());
				paymentPlanRepository.save(ppe);
				logger.info("### 6W5549建行签署合同成功，更新计划付款成功payment={}", ppe);
			}
			Integer coo = creditRecordRepository.updateBySignContract(cre.getTid(), CreditUnusualStatus.NORMAL.toString()
					, null, cre.getCreditStatus(),creditRecordFeedback.getAr_due_date());
			if(coo != 1){
				logger.error("合同循环签订任务失败，invoiceNoCode = {}", cre.getInvoiceNoCode());
			}
			//新增合同签订的历时记录
			creditUserServiceUtil.createRecordTime(cre.getTid(), CreditStatus.SUBSTITUTE_CONTRACT.toString());
			logger.info("### 6W5549建行签署合同成功，更新融资状态，融资到期日成功，融资编号recordNo={},融资状态creditStatus={},融资到期日loanDateCcb={}", cre.getRecordNo(),cre.getCreditStatus(),cre.getLoanDateCcb());
		} else {
			// 审核状态更新为合同签署失败
			/**
			 * 实际付款状态改为未付款
			 */
			ppe.setPayState(ZhucaiConstant.PaymentPlanStatus.NOT_PAYMENT_STATUS);
			
		    paymentPlanRepository.updatePayState(ppe.getTid(),ZhucaiConstant.PaymentPlanStatus.NOT_PAYMENT_STATUS);
			logger.info("### 6W5549建行驳回合同,融资编号recordNo={}对应的付款计划id={}的付款计划状态改为未付款成功payState={}",cre.getRecordNo(),cre.getPaymentId(),ZhucaiConstant.PaymentPlanStatus.NOT_PAYMENT_STATUS);
			cre.setCreditStatus(CreditStatus.WAIT_SUBMIT.toString());
			cre.setCreditUnusualStatus(CreditUnusualStatus.CONTRACT_REJECT.toString());
			cre.setRejectReason("建行驳回");
			Integer coo = creditRecordRepository.updateUnusualStatus(HelpConstant.Status.delete, cre.getTid(), CreditUnusualStatus.CONTRACT_REJECT.toString()
					, cre.getRejectReason(), cre.getCreditStatus());
			if(coo != 1){
				logger.error("合同循环签订任务失败，invoiceNoCode = {}", cre.getInvoiceNoCode());
			}else{
				logger.info("### 6W5549建行驳回合同,融资编号recordNo={}的融资记录状态CreditStatus={}改为合同签署失败,",cre.getRecordNo(),CreditStatus.WAIT_SUBMIT.toString(),ZhucaiConstant.PaymentPlanStatus.NOT_PAYMENT_STATUS);
			}
		
			//删除融资历时记录
			creditRecordTimeRepository.deleteRecordTimeByRecordId(cre.getTid());
		}
		
	}
	/**
	 * 支用信息反馈 6W5528
	 * @throws Exception 
	 * 
	 * @date 2017年11月29日 @user hsg
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	private void drawMoneyFeedBack() throws Exception {
		
		List<String> creditStatusList = new ArrayList<String>();
		
		creditStatusList.add(CreditStatus.PENDING_WITHDRAWAL.toString());//待支取
		//兼容6W5528在6W5549前先来，处理
		creditStatusList.add(CreditStatus.SUBSTITUTE_CONTRACT.toString());//待签合同
		
		List<CreditRecordEntrity> crList = creditRecordRepository.findByCreditStatusAndStatusNot(
				creditStatusList, HelpConstant.Status.delete,CrProdType.E_POINT.toString());
		if (CollectionUtils.isEmpty(crList)) {
			// 判断是否有在待支取中的待支取融资记录，如果无就不去查询
			return;
		}
		// 调用接口返回集合
		List<DrawFinancingMoney> rs = ccbeService.drawFinancingMoney();
		if (CollectionUtils.isEmpty(rs)) {
			return;
		}
		for (DrawFinancingMoney drawFinancingMoney : rs) {
			
			//发票号
			String bill_num = drawFinancingMoney.getBill_num();
			//当发票号为空跳出此循环
			if (bill_num == null) {
				continue;
			}
			
			// 判断支取是否成功,不成功跳出循环
			if (!drawFinancingMoney.getLoan_ind().trim().equals("1")) {
				continue;
			}
			//此次的预付款金额
			BigDecimal prepaymentAmt = BigDecimal.valueOf(drawFinancingMoney.getPrepayment_amt());
			
			// 根据@|@切割单据号
			String[] bill_arr = bill_num.split("@\\|@");
			
			List<String> bill_list = new ArrayList<String>();
			for (int i = 0; i < bill_arr.length; i++) {
				bill_list.add(bill_arr[i]);
			}
			// 按照还款日期和发票号融资记录
			List<CreditRecordEntrity> obj_list = creditRecordRepository
					.findByBillArr(HelpConstant.Status.delete, bill_list);
			logger.info("支取编号payoutNum={}的支取金额池为prepaymentAmt={}",drawFinancingMoney.getPayout_num(),drawFinancingMoney.getPrepayment_amt());
			for (int i = 0; i < obj_list.size(); i++) {
				
				CreditRecordEntrity cre = obj_list.get(i);
				//根据支用编号和发票号查询此次的融资记录
				FinanceDrawEntity financeDrawEntity = financeDrawRepository.findByStatusNotAndPayoutNumAndInvoiceNoCode(HelpConstant.Status.delete,drawFinancingMoney.getPayout_num(),cre.getInvoiceNoCode());
				//判断这笔发票是否被支取
				if(financeDrawEntity!=null){
					prepaymentAmt=BigDecimal.ZERO.add(prepaymentAmt.subtract(financeDrawEntity.getDrawAmount()));
					logger.info("!支取编号payoutNum={},金额池被发票号invoiceNo={},金额池的金额prepaymentAmt={}被消费掉surplusDrawMount={},金额池剩余subPrepaymentAmt={}",
							drawFinancingMoney.getPayout_num(),cre.getInvoiceNoCode(),prepaymentAmt.add(financeDrawEntity.getDrawAmount()),financeDrawEntity.getDrawAmount(),prepaymentAmt);
					continue;
				}
				logger.info("支取编号payoutNum={}发票号为inoiceNo={}消费支取金额池开始：",drawFinancingMoney.getPayout_num(),cre.getInvoiceNoCode());
				prepaymentAmt= drawAmt(cre,prepaymentAmt,drawFinancingMoney);
				logger.info("支取编号payoutNum={}的金额池剩余金额subPrepaymentAmt={}",drawFinancingMoney.getPayout_num(),prepaymentAmt);
				//金额池被消费完跳出循环
				if(prepaymentAmt.compareTo(BigDecimal.ZERO)==0){
					logger.info("支取编号payoutNum={}的金额池刚好被消费完了跳出循环",drawFinancingMoney.getPayout_num());
					break;
				}
				if(prepaymentAmt.compareTo(BigDecimal.ZERO)==-1){
					logger.info("支取编号payoutNum={}的金额池被异常消费完了跳出循环,金额池剩余amt={}",drawFinancingMoney.getPayout_num(),prepaymentAmt);
					ProblemRecordEntrity problemRecordEntrity = new ProblemRecordEntrity();
					problemRecordEntrity.setOperPhone("18179810921");
					problemRecordEntrity.setOperTime(new Date());
					problemRecordEntrity.setOperlevel("A");
					problemRecordEntrity.setOperStatus(0);
					problemRecordEntrity.setOutId(cre.getTid());
					String problem = "支取编号为"+drawFinancingMoney.getPayout_num()+"金额池"+drawFinancingMoney.getPrepayment_amt()+"元,被异常消费完了"+",发票号为"+cre.getInvoiceNoCode()+"，剩余金额为"+prepaymentAmt;
					problemRecordEntrity.setProblemRemark(problem);
					problemSericeImpl.setProblem(problemRecordEntrity);
					break;
				}
			}
		}
	}
	/**
	 * 支取方法返回未支取的金额
	 */
	private BigDecimal drawAmt(CreditRecordEntrity cre,BigDecimal prepaymentAmt,DrawFinancingMoney drawFinancingMoney){
		//根据发票tid查询发票信息
		CreditInvoiceEntity invoiceInfo = creditInvoiceRepository.findOne(cre.getInvoiceTid());
		//支取率
		BigDecimal drawRate = BigDecimal.valueOf(Double.valueOf(drawFinancingMoney.getFnc_rto()));
		//融资金额=账款金额*支取率
		BigDecimal creditAmt =cre.getCreditGetAmount().multiply(drawRate).setScale(2,BigDecimal.ROUND_HALF_UP);		
		//此融资记录的支取金额
		BigDecimal drawAmount = cre.getDrawAmount()==null?BigDecimal.ZERO:cre.getDrawAmount();
		//此融资记录的待支取金额
		BigDecimal surplusDrawMount = creditAmt.subtract(drawAmount);
		
		//定义支用的实体
		FinanceDrawEntity fde = new FinanceDrawEntity();
		fde.setOutId(cre.getTid());
		fde.setDrawTime(new Date());
		Date Loan_date = TimeUtils.changeDate3(drawFinancingMoney.getLoan_date());
		fde.setLoanDate(Loan_date);
		fde.setEnterpriseName(drawFinancingMoney.getCust_name());
		//支取的发票号发票代码
		fde.setInvoiceNoCode(cre.getInvoiceNoCode());
		//支取的企业id
		fde.setEnterpriseId(cre.getParticipatorEnterpriseId());
		//商家类型
		fde.setEntType(EntType.SUPPLIER.toString());
		//发票金额
		fde.setInvoiceAmount(invoiceInfo.getInvoiceAmount());
		//支取的组织机构编号
		fde.setOrgNum(cre.getOriginatorOrgnCode());
		//支用编号
		fde.setPayoutNum(drawFinancingMoney.getPayout_num());
		//支取金额池消费支取金额金额
		BigDecimal subPrepaymentAmt = prepaymentAmt.subtract(surplusDrawMount);
		
		int compareTo = subPrepaymentAmt.compareTo(BigDecimal.ZERO);
		cre.setDrawRate(drawRate==null?BigDecimal.ZERO:drawRate);
		cre.setCreditAmount(creditAmt);
		//金额池刚好被消费完
		if(compareTo==0){
			fde.setDrawAmount(prepaymentAmt);
			cre.setDrawAmount(drawAmount.add(prepaymentAmt));
			cre.setCreditStatus(CreditStatus.REPAYMENT.toString());
			creditRecordRepository.save(cre);
			financeDrawRepository.save(fde);
			logger.info("支取编号payoutNum={},金额池被发票号invoiceNo={},消费完，金额池的金额prepaymentAmt={}被消费掉surplusDrawMount={},金额池剩余subPrepaymentAmt={}",drawFinancingMoney.getPayout_num(),cre.getInvoiceNoCode(),prepaymentAmt,surplusDrawMount,prepaymentAmt.subtract(surplusDrawMount));
		//
			//金额池没被消费完
		}else if(compareTo==1){
			fde.setDrawAmount(surplusDrawMount);
			cre.setCreditStatus(CreditStatus.REPAYMENT.toString());
			cre.setDrawAmount(drawAmount.add(surplusDrawMount));
			creditRecordRepository.save(cre);
			financeDrawRepository.save(fde);
			logger.info("支取编号payoutNum={},金额池被发票号invoiceNo={},消费完，金额池的金额prepaymentAmt={}被消费掉surplusDrawMount={},金额池剩余subPrepaymentAmt={}",
					drawFinancingMoney.getPayout_num(),cre.getInvoiceNoCode(),prepaymentAmt,surplusDrawMount,prepaymentAmt.subtract(surplusDrawMount));		//金额池被消费完
		
		}else{
			fde.setDrawAmount(prepaymentAmt);
			cre.setDrawAmount(drawAmount.add(prepaymentAmt));
			creditRecordRepository.save(cre);
			financeDrawRepository.save(fde);
			logger.info("支取编号payoutNum={},金额池被发票号invoiceNo={}消费完，金额池的金额prepaymentAmt={}被消费掉surplusDrawMount={},金额池剩余subPrepaymentAmt={},并且融资编号为recordId={}只支取部分金额amt={}",
					drawFinancingMoney.getPayout_num(),cre.getInvoiceNoCode(),prepaymentAmt,surplusDrawMount,prepaymentAmt,cre.getRecordNo(),prepaymentAmt.subtract(surplusDrawMount));
		}
		//判断是否有支取历时记录
		List<CreditRecordTimeEntrity> findByCrRecordIdAndRecordStatus = creditRecordTimeRepository.findByCrRecordIdAndRecordStatus(cre.getTid(), CreditStatus.PENDING_WITHDRAWAL.toString());
		if(CollectionUtils.isEmpty(findByCrRecordIdAndRecordStatus)){
			//新增支取历时记录
			creditUserServiceUtil.createRecordTime(cre.getTid(), CreditStatus.PENDING_WITHDRAWAL.toString());
		}
		
		return subPrepaymentAmt;
	}
	/**
	 * 付款信息反馈 6W5564(采购商还款)
	 * @throws Exception 
	 * 
	 * @date 2017年11月30日 @user hsg
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	private void findCreditRecordPayment() throws Exception {
		
		List<String> creditStatusList = new ArrayList<String>();
		
		creditStatusList.add(CreditStatus.REPAYMENT.toString());//待还款
		creditStatusList.add(CreditStatus.PENDING_WITHDRAWAL.toString());//待支取
		
		List<CreditRecordEntrity> rList = creditRecordRepository
				.findByCreditStatusAndStatusNot(creditStatusList, HelpConstant.Status.delete,CrProdType.E_POINT.toString());
		
		if(CollectionUtils.isEmpty(rList)){
			//当没有需要获取的就直接返回
			return;
		}
		logger.info("付款信息反馈 6W5564 接口开始");
		// 调用建行接口返回数据集合
		List<CreditRecordPayment> rs = ccbeService.creditRecordPayment();
		
		for (CreditRecordPayment creditRecordPayment : rs) {
			// 获取单据字符串
			String bill_num = creditRecordPayment.getBill_num();
			// 获取付款集合字符串
			String bill_amt = creditRecordPayment.getBill_amt();
			// 按照@|@分割单据字符串
			String[] bill_num_arr = bill_num.split("@\\|@");
			// 按照@|@分割付款金额字符串
			String[] bill_amt_arr = bill_amt.split("@\\|@");
			if(StringUtils.isEmpty(bill_num)){
				//判断发票不能为空
				continue;
			}
			for (int i = 0; i < bill_num_arr.length; i++) {
				//根据反馈序号和发票号查询付款记录信息
				List<FinanceRepaymentEntity> freList= financeRepaymentRepository.findByStatusNotAndSerialNumAndInvoiceNoCode(HelpConstant.Status.delete,creditRecordPayment.getSerial_num(),bill_num_arr[i].toString());
				//当freList不为空表示已记录过，跳出循环
				if(CollectionUtils.isNotEmpty(freList)){
					continue;
				}
				// 付款的实体
				FinanceRepaymentEntity fre = new FinanceRepaymentEntity();
				fre.setEntType(EntType.PURCHASER.toString());
				// 根据单据号查询融资信息
				CreditRecordEntrity cre = creditRecordRepository
						.findByStatusNotAndInvoiceNoCode(HelpConstant.Status.delete, bill_num_arr[i]);
				if (cre == null||CreditStatus.REPAYMENTS.toString().equals(cre.getCreditStatus())) {
					//当为空跳出此循环或已销账跳出循环
					continue;
				}
				EntAccountEntity eae = entAccountRepository.findByTid(cre.getOriginator());
				//此发票对应的金额
				Double amt = Double.valueOf(bill_amt_arr[i]);
				BigDecimal invo_amt = BigDecimal.valueOf(amt);
				//设置采购商名称
				fre.setEnterpriseName(eae.getEnterpriseName());
				fre.setEnterpriseId(eae.getEnterpriseId());
				fre.setOrgNum(eae.getOrgNum());
				fre.setInvoiceNoCode(cre.getInvoiceNoCode());
				// 设置操作记录的外界关联id
				fre.setOutId(cre.getTid());
				//设置发票金额
				fre.setPaymentAmount(invo_amt==null?BigDecimal.ZERO:invo_amt);
				//设置反馈序号
				fre.setSerialNum(creditRecordPayment.getSerial_num());
				fre.setPaymentTime(new Date());
				fre.setEntType(EntType.PURCHASER.toString());
				//此融资记录的还款金额
				BigDecimal repaymentAmount=cre.getRepaymentAmount()==null?BigDecimal.ZERO:cre.getRepaymentAmount();
				
				// 本次付款，是否成功销账的标识(1-是;0-否),付款成功更新融资记录已还款信息
				if (creditRecordPayment.getWrite_off_ind() != null
						&& creditRecordPayment.getWrite_off_ind().trim().equals("1")) {
					cre.setCreditStatus(CreditStatus.REPAYMENTS.toString());
				}
				//总还款金额 已还款金额加上现在还款金额等于总还款金额
				BigDecimal addRepaymentAmount = repaymentAmount.add(invo_amt);
				cre.setRepaymentAmount(addRepaymentAmount);
				//采购商还款金额
				BigDecimal purRepaymentAmount = cre.getPurRepaymentAmount()==null?BigDecimal.ZERO:cre.getPurRepaymentAmount();
				purRepaymentAmount = BigDecimal.ZERO.add(purRepaymentAmount.add(invo_amt==null?BigDecimal.ZERO:invo_amt));
				cre.setPurRepaymentAmount(purRepaymentAmount);
				
				creditRecordRepository.save(cre);
				financeRepaymentRepository.save(fre);
				
				logger.info("付款信息反馈 6W5564 接口单据号为" + bill_num_arr[i] + "的还款金额变为" + addRepaymentAmount);
				
				//新增还款历时记录
				creditUserServiceUtil.createRecordTime(cre.getTid(), CreditStatus.REPAYMENT.toString());
			}
		}

	}

	/**
	 * 扣款信息反馈 6W5550(供应商还款)
	 * @throws Exception 
	 * 
	 * @date 2017年11月29日 @user hsg
	 */
	private void findCreditRecordDebit() throws Exception {
		StringBuilder str = new StringBuilder();
				str.append("扣款信息反馈 6W5550 接口开始");
				List<String> creditStatusList = new ArrayList<String>();
				
				creditStatusList.add(CreditStatus.REPAYMENT.toString());//待还款
				creditStatusList.add(CreditStatus.PENDING_WITHDRAWAL.toString());//待支取
				//查询是否存在待还款的记录
				List<CreditRecordEntrity> rList = creditRecordRepository
						.findByCreditStatusAndStatusNot(creditStatusList, HelpConstant.Status.delete,CrProdType.E_POINT.toString());
				if(CollectionUtils.isEmpty(rList)){
					//当没有需要获取的就直接返回
					return;
				}
				// 调用建行接口返回数据集合
				List<CreditRecordDebit> rs=new ArrayList<CreditRecordDebit>();
					rs = ccbeService.creditRecordDebit();
					if(CollectionUtils.isEmpty(rs)){
						//当为空就直接返回
						return;
					}
					ProblemRecordEntrity problemRecordEntrity = new ProblemRecordEntrity();
					problemRecordEntrity.setOperPhone("18179810921");
					problemRecordEntrity.setOperTime(new Date());
					problemRecordEntrity.setOperlevel("A");
					problemRecordEntrity.setOperStatus(0);
					String problem = "扣款信息反馈6W5550执行了";
					problemRecordEntrity.setProblemRemark(problem);
					problemSericeImpl.setProblem(problemRecordEntrity);
//				for (CreditRecordDebit creditRecordDebit : rs) {
//					//根据反馈序号查询扣款记录
//					FinanceDebitEntity fdee = financeDebitRepository.findBySerialNum(creditRecordDebit.getSerial_num());
//					if(fdee!=null){
//						//当不为空表示已分配过跳过
//						continue;
//					}
//					// 扣款记录实体bean
//					FinanceDebitEntity financeDebitEntity = new FinanceDebitEntity();
//					//根据支用编号查询支用记录
//					List<FinanceDrawEntity> fdeList=financeDrawRepository.findByStatusNotAndPayoutNum(HelpConstant.Status.delete, creditRecordDebit.getPayout_num());
//					for (FinanceDrawEntity financeDrawEntity : fdeList) {
//						//支用编号的查询出的支用金额
////						BigDecimal drawAmountE = financeDrawEntity.getDrawAmount()==null?BigDecimal.ZERO:financeDrawEntity.getDrawAmount();
//						//根据发票编号查询融资记录
//						CreditRecordEntrity cre =  creditRecordRepository.findByInvoiceNoCodeAndCreditStatusNotAndStatusNot(financeDrawEntity.getInvoiceNoCode(),CreditStatus.BREACH_OF_CONTRACT.toString(), HelpConstant.Status.delete);
//						//查询此次的所有扣款金额
//						//归还贷款本金
//						Double pay_principal_amt = creditRecordDebit.getPay_principal_amt()==null?0:creditRecordDebit.getPay_principal_amt();
//						//一般结算户扣款金额
//						Double clearance_account_amt=creditRecordDebit.getClearance_account_amt()==null?0:creditRecordDebit.getClearance_account_amt();
//						//风险池扣款金额
//						Double risk_pool_amt = creditRecordDebit.getRisk_pool_amt()==null?0:creditRecordDebit.getRisk_pool_amt();
//						//保证金账户扣款金额
//						Double guarantee_account_amt = creditRecordDebit.getGuarantee_account_amt()==null?0:creditRecordDebit.getGuarantee_account_amt();
//						//代还账户扣款金额
//						Double platform_account_amt = creditRecordDebit.getPlatform_account_amt()==null?0:creditRecordDebit.getPlatform_account_amt();
//						//此次所有扣款金额
//						Double allAmt=platform_account_amt+guarantee_account_amt+risk_pool_amt+clearance_account_amt+pay_principal_amt;
//						//根供应商金融id查询金融信息
//						EntAccountEntity eae = entAccountRepository.findByTid(cre.getParticipator());
//						//付款记录实体
//						FinanceRepaymentEntity fre=new FinanceRepaymentEntity();
//						//新增付款记录<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
//						//商家类型
//						fre.setEntType(EntType.SUPPLIER.toString());
//						//商家姓名
//						fre.setEnterpriseName(eae.getEnterpriseName());
//						fre.setEnterpriseId(eae.getEnterpriseId());
//						fre.setOrgNum(eae.getOrgNum());
//						
//						//发票编号
//						fre.setInvoiceNo(financeDrawEntity.getInvoiceNo());
//						//发票号和发票代码
//						fre.setInvoiceNoCode(financeDrawEntity.getInvoiceNoCode());
//						//付款金额
//						fre.setPaymentAmount(BigDecimal.valueOf(allAmt));
//						//外部关联id
//						fre.setOutId(cre.getTid());
//						//还款时间
//						fre.setPaymentTime(new Date());
//						//更新融资记录里的还款金额>>>>>>>>>>>>>>>>>>>>>
//						//供应商商还款金额
//						BigDecimal supRepaymentAmount = cre.getSupRepaymentAmount()==null?BigDecimal.ZERO:cre.getSupRepaymentAmount();
//						//更新最新供应商还款金额
//						cre.setSupRepaymentAmount(supRepaymentAmount.add(BigDecimal.valueOf(allAmt)));
//						//融资记录的总共还款金额
//						BigDecimal allRepaymentAmount = cre.getRepaymentAmount()==null?BigDecimal.ZERO:cre.getRepaymentAmount();
//						//更新融资记录里的总共还款金额
//						cre.setRepaymentAmount(allRepaymentAmount.add(BigDecimal.valueOf(allAmt)));
//						//总共还款金额
//						BigDecimal allAmount = allRepaymentAmount.add(BigDecimal.valueOf(allAmt));
//						//判断融资金额和总共还款金额是否相等，相等表示还款完成
//						BigDecimal creditAmt = cre.getCreditAmount()==null?BigDecimal.ZERO:cre.getCreditAmount();
//						int compareTo = creditAmt.compareTo(allAmount);
//						if(compareTo==0||compareTo==-1){
//							cre.setCreditStatus(CreditStatus.REPAYMENTS.toString());
//						}
//						financeRepaymentRepository.save(fre);
//						creditRecordRepository.save(cre);
//					}
//					//新增扣款记录
//					financeDebitEntity.setPayoutNum(creditRecordDebit.getPayout_num());
//					if (creditRecordDebit.getDeduct_ind().equals("1")) {
//						financeDebitEntity.setDeductInd(DeductInd.ONE.toString());
//					} else if (creditRecordDebit.getDeduct_ind().equals("2")) {
//						financeDebitEntity.setDeductInd(DeductInd.TWO.toString());
//					} else if (creditRecordDebit.getDeduct_ind().equals("3")) {
//						financeDebitEntity.setDeductInd(DeductInd.THREE.toString());
//					} else if (creditRecordDebit.getDeduct_ind().equals("4")) {
//						financeDebitEntity.setDeductInd(DeductInd.FOUR.toString());
//					}
//					financeDebitEntity.setSerialNum(creditRecordDebit.getSerial_num());
//					financeDebitEntity.setContractNumCcb(creditRecordDebit.getContract_num());
//					financeDebitEntity.setEntType(EntType.SUPPLIER.toString());
//					financeDebitRepository.save(financeDebitEntity);
//					
//				}
				
	}
}
